package com.maybach.workflow.core.config.parser;


import com.maybach.util.AssertUtil;
import com.maybach.workflow.common.api.enums.NodeTypeEnum;
import com.maybach.workflow.common.api.node.DecisionNode;
import com.maybach.workflow.common.api.node.TransactionNode;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by well on 15/6/11.
 */
public class DecisionParser extends AbstractParser<DecisionNode> {

    public DecisionParser() {
        super(NodeParser.NODE_NAME_DECISION);
    }

    @Override
    public DecisionNode createNode() {
        return new DecisionNode();
    }

    @Override
    public void parseSpecial(Element element, DecisionNode specialNode) {
        NodeList children = element.getChildNodes();
        Parser parse = NodeParser.getParserMap().get(NodeTypeEnum.transaction.name());
        List<TransactionNode> transactionNodeList = new ArrayList<TransactionNode>();
        if (null != children) {
            for (int i = 0; i < children.getLength(); i++) {
                Node node = children.item(i);
                if (null != node && node.getNodeType() == Node.ELEMENT_NODE) {
                    TransactionNode transactionNode = (TransactionNode) parse.parse((Element) node);
                    if (null != transactionNode) {
                        transactionNodeList.add(transactionNode);
                    }
                }
            }
        }
        specialNode.setTransactionNodeList(transactionNodeList);
    }

    @Override
    public void check(DecisionNode decisionNode) {
        super.check(decisionNode);
        AssertUtil.notEmpty(decisionNode.getTransactionNodeList(), "transactionNodeList");
    }
}
